package com.paisheng.justlife.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.paisheng.justlife.R;
import com.paisheng.justlife.adapter.RubbishListAdapter;
import com.paisheng.justlife.appliction.MyApplication;
import com.paisheng.justlife.bean.ComBean;
import com.paisheng.justlife.bean.Waste;
import com.paisheng.justlife.common.MenuType;
import com.paisheng.justlife.common.SerialNumber;
import com.paisheng.justlife.utils.DeviceInfoUtils;
import com.paisheng.justlife.utils.MyFunc;
import com.paisheng.justlife.utils.SerialPortUtils;
import com.paisheng.justlife.utils.SharedPreferencesHelper;
import com.paisheng.justlife.utils.ToastUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ConfirmPaymentActivity extends Activity implements View.OnClickListener {
    private TextView tv_time,tv_money;
    private ListView lv_rubbish_list;
    private Button btn_stop, btn_confirm_paymen;
    private ImageView iv_step;
    private List<Waste> listWaste;
    private List<Waste> parseArray = new ArrayList<>();
    private SerialPortUtils serialPortUtils;
    private String sMsg;
    private int recLen = 60;
    Timer timer = new Timer();
    private SharedPreferencesHelper spfh;
    private String imei;
    private String sharedPreference;
    private Intent intent;
    private List<Waste> itemList = new ArrayList<>();
    boolean flag = true; //判断门是否一开，开门为false
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_payment);
        imei = DeviceInfoUtils.getMacAddress(this);
        MyApplication content = (MyApplication) getApplicationContext();
        serialPortUtils = content.serialPortUtils;
        initview(); //初始化View
        initData(); //初始化数据
        eventListening(); //串口监听和回调
    }

    @Override
    protected void onResume() {
        super.onResume();
        timer.schedule(task, 1000, 1000);
    }

    private void initview() {
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_money = (TextView) findViewById(R.id.tv_money);
        lv_rubbish_list = (ListView) findViewById(R.id.lv_rubbish_list);
        btn_stop = (Button) findViewById(R.id.btn_stop);
        iv_step = (ImageView) findViewById(R.id.iv_step);
        btn_confirm_paymen = (Button) findViewById(R.id.btn_confirm_paymen);
        btn_stop.setOnClickListener(this);
        btn_confirm_paymen.setOnClickListener(this);
    }


    public TimerTask task = new TimerTask() {
        @Override
        public void run() {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recLen--;
                    tv_time.setText("" + recLen);
                    if (recLen <= 0) {
                        startActivity(new Intent(ConfirmPaymentActivity.this,MainActivity.class));
                        timer.cancel();
                    }
//                    Log.e("zpan","======remainTime=====" + recLen);

                }
            });

        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_stop:
                startActivity(new Intent(this, MainActivity.class));
                break;
            case R.id.btn_confirm_paymen:
                for (Waste waste : listWaste) {
                    String name = waste.getName();
                    switch (name) {
                        case (MenuType.CLOTHES):
                            serialPortUtils.sendSerialPort(SerialNumber.DOWN_OPEN_CLOTHES);
                            delectWasteName(name);
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            break;
                        case (MenuType.PAPER):
                            serialPortUtils.sendSerialPort(SerialNumber.DOWN_OPEN_PAPER);
                            delectWasteName(name);
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            break;
                        case (MenuType.PLASTIC):
                            serialPortUtils.sendSerialPort(SerialNumber.DOWN_OPEN_PLASTIC);
                            delectWasteName(name);
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            break;
                        case (MenuType.METAL):
                            serialPortUtils.sendSerialPort(SerialNumber.DOWN_OPEN_METAL);
                            delectWasteName(name);
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            break;
                    }


                }
                break;
        }
    }

    private void delectWasteName(String name) {
        if(parseArray!= null){
            Iterator<Waste> iterator = parseArray.iterator();
            while(iterator.hasNext()){
                Waste waste = iterator.next();
                if(waste.getName().equals(name)){
                    iterator.remove();
                }
            }
            String jsonString = JSON.toJSONString(parseArray);
            spfh.put(imei,jsonString);
        }

    }

    private void initData() {
        intent = getIntent();
        listWaste = (List<Waste>) intent.getSerializableExtra("listWaste"); //获取回收的种类
        spfh = new SharedPreferencesHelper(this, "CAST_MESSAGE"); //获取spf对象
        sharedPreference = (String) spfh.getSharedPreference(imei, String.class); //获取当前存储垃圾的信息
        parseArray = JSON.parseArray(sharedPreference, Waste.class); //JSON转换集合
        BigDecimal sum = BigDecimal.ZERO;

        if(parseArray!=null){
            for (Waste waste : listWaste) {             //回收箱的垃圾信息
                for (Waste wasteList : parseArray) {
                    if(wasteList.getName().equals(waste.getName())){
                        itemList.add(wasteList);
                        sum = sum.add(new BigDecimal(wasteList.getTotalMoney()));
                    }

                }

            }
            tv_money.setText(sum+"");
            lv_rubbish_list.setAdapter(new RubbishListAdapter(this,itemList, MenuType.RECYCLE));
        }


    }



    private void eventListening() {
        MyApplication content = (MyApplication) getApplicationContext();
        serialPortUtils = content.serialPortUtils;
        this.serialPortUtils.setOnDataReceiveListener(new SerialPortUtils.OnDataReceiveListener() { //获取回调监听
            @Override
            public void onDataReceive(ComBean ComRecData) {
                sMsg = MyFunc.ByteArrToHex(ComRecData.bRec);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (sMsg.equals(SerialNumber.DOWN_RETURN_PLASTIC)
                                || sMsg.equals(SerialNumber.DOWN_RETURN_METAL)
                                || sMsg.equals(SerialNumber.DOWN_RETURN_PAPER)
                                || sMsg.equals(SerialNumber.DOWN_RETURN_CLOTHES)
                        ) {

                            if(flag){
                                flag =false;
                                startActivity(new Intent(ConfirmPaymentActivity.this,ClaimGoodsActivity.class));
                                intent = new Intent();
                                intent.setAction("com.paisheng.justlife.service.SerialService");
                                intent.putExtra("openBoor",false);
                                sendBroadcast(intent);
                            }
                        }
                    }
                });
            }
        });
    }



    @Override
    protected void onPause() {
        super.onPause();
        timer.cancel();
        ToastUtil.cancelToast();
        finish();
    }
}
